package com.sywb.chuangyebao.contract;

import android.app.Activity;
import android.os.CountDownTimer;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.ViewGroup;
import android.view.animation.TranslateAnimation;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.sywb.chuangyebao.R;
import com.sywb.chuangyebao.bean.BusinessInfo;
import com.sywb.chuangyebao.utils.DateTimeUtils;
import com.sywb.chuangyebao.utils.GlideUtils;
import com.sywb.chuangyebao.utils.HttpCallback;
import com.sywb.chuangyebao.utils.HttpUtils;
import com.sywb.chuangyebao.view.BusinessTVDetailActivity;
import com.sywb.chuangyebao.view.WebActivity;

import org.bining.footstone.adapter.BasePagerAdapter;
import org.bining.footstone.adapter.BaseRecyclerAdapter;
import org.bining.footstone.adapter.BaseRecyclerDivider;
import org.bining.footstone.adapter.ViewHolderHelper;
import org.bining.footstone.adapter.listener.OnItemChildClickListener;
import org.bining.footstone.adapter.listener.OnItemClickListener;
import org.bining.footstone.log.Logger;
import org.bining.footstone.mvp.IView;
import org.bining.footstone.presenter.BasePresenter;
import org.bining.footstone.utils.ScreenUtils;
import org.bining.footstone.widget.PullToRefreshView;

import java.util.ArrayList;
import java.util.List;

public interface BusinessTVContract {

    interface View extends IView {
        void startLive(String liveUrl);

        ViewPager getViewPager();

        android.view.View getTabCursor();
    }

    class Presenter extends BasePresenter<View> {

        private ViewPager viewPager;
        private android.view.View tabCursor;

        private List<RecyclerView> commonRecyclers;
        private List<android.view.View> commonLines;
        private List<RelativeLayout> commonNoDatas;
        private List<BaseRecyclerAdapter> adapters;

        private int tabChildWidth;
        private int currentIndex;

        private CountDownTimer mCountDownTimer = null;

        @Override
        public void onStart() {
            this.viewPager = mView.getViewPager();
            this.tabCursor = mView.getTabCursor();

            commonLines = new ArrayList<>();
            commonRecyclers = new ArrayList<>();
            commonNoDatas = new ArrayList<>();
            adapters = new ArrayList<>();

            List<android.view.View> viewList = new ArrayList<>();
            viewList.add(initWaitPassMsgPage(0));
            viewList.add(initWaitPassMsgPage(1));

            this.viewPager.setAdapter(new BasePagerAdapter(viewList));
            this.viewPager.setOffscreenPageLimit(viewList.size());
            this.viewPager.setCurrentItem(0);

            initTabWidth();
            getRoomLiveUrl();
            // getCreateTvList(-1);
        }

        /**
         * 初始化View
         */
        private android.view.View initWaitPassMsgPage(final int type) {
            android.view.View view = mActivity.getLayoutInflater().inflate(R.layout.layout_businesstv_list, null);
            RecyclerView commonRecycler = view.findViewById(R.id.rv_businesstv_program);
            android.view.View v_businesstv_line = view.findViewById(R.id.v_businesstv_line);
            RelativeLayout commonNoData = view.findViewById(R.id.common_nodata);
            commonRecyclers.add(commonRecycler);
            commonLines.add(v_businesstv_line);
            commonNoDatas.add(commonNoData);

            commonRecycler.setLayoutManager(new LinearLayoutManager(mActivity));

            BaseRecyclerDivider divider = new BaseRecyclerDivider();
            divider.setColor(ContextCompat.getColor(mContext, android.R.color.transparent));
            divider.setTopOffsets(true);
            divider.setDivider((int) mContext.getResources().getDimension(R.dimen.dp_12));
            commonRecycler.addItemDecoration(divider);

            BusinessTVAdapter businessTVAdapter = new BusinessTVAdapter(mActivity);
            businessTVAdapter.setOnItemClickListener(new OnItemClickListener() {
                @Override
                public void onItemClick(android.view.View view, int i) {
//            BusinessInfo businessInfo = recyclerAdapter.getItem(postion);
//            mView.advance(WebActivity.class, "项目详情", businessInfo.url);
                }
            });
            switch (type) {
                case 0:
//                    commonRefresh.setOnRefreshListener(new PullToRefreshView.OnRefreshListener() {
//                        @Override
//                        public void onRefresh(PullToRefreshView pullToRefreshView) {
//                            pageNos[0] = 1;
//                            // 加载节目预告
//                        }
//                    });
//
//                    businessTVAdapter.openLoadMore(R.layout.layout_loading, Constants.PAGESIZE);
//                    businessTVAdapter.setOnLoadMoreListener(new OnLoadMoreListener() {
//                        @Override
//                        public void onLoadMoreClick() {
//                            pageNos[0]++;
//                            // 加载节目预告
//                        }
//                    });
                    businessTVAdapter.setOnItemChildClickListener(new OnItemChildClickListener() {
                        @Override
                        public void onItemChildClick(android.view.View view, int postion) {
                            BusinessInfo businessInfo = (BusinessInfo) adapters.get(0).getItem(postion);
                            switch (view.getId()) {
                                case R.id.iv_businesstv_face:
                                case R.id.tv_businesstv_name:
                                case R.id.tv_businesstv_goodat:
                                case R.id.tv_businesstv_other:
                                    mView.advance(WebActivity.class, "项目详情", businessInfo.url);
                                    break;
                                case R.id.tv_businesstv_consult:
                                    if (businessInfo.status == 3) {
                                        if (!businessInfo.is_reservation) {
                                            getCreateTvReservation(postion, businessInfo.index, businessInfo.tvp_id);
                                        }
                                    } else {
                                        mView.advance(WebActivity.class, "项目详情", businessInfo.url);
                                    }
                                    break;
                            }
                        }
                    });
                    break;
                case 1:
                    businessTVAdapter.setOnItemChildClickListener(new OnItemChildClickListener() {
                        @Override
                        public void onItemChildClick(android.view.View view, int postion) {
                            BusinessInfo businessInfo = (BusinessInfo) adapters.get(1).getItem(postion);
                            switch (view.getId()) {
                                case R.id.iv_businesstv_face:
                                case R.id.tv_businesstv_name:
                                case R.id.tv_businesstv_goodat:
                                case R.id.tv_businesstv_other:
                                    mView.advance(WebActivity.class, "项目详情", businessInfo.url);
                                    break;
                                case R.id.tv_businesstv_consult:
                                    mView.advance(BusinessTVDetailActivity.class, businessInfo.tvp_id);
                                    break;
                            }
                        }
                    });

                    break;
            }

            commonRecycler.setAdapter(businessTVAdapter);
            adapters.add(businessTVAdapter);

            isNoData(type);

            return view;
        }

        /**
         * 初始化指示条宽度
         */
        private void initTabWidth() {
            this.tabChildWidth = ScreenUtils.getScreenWidth() / 2;
            int cursorTextWidth = tabChildWidth;
            ViewGroup.MarginLayoutParams p1 = (ViewGroup.MarginLayoutParams) this.tabCursor.getLayoutParams();
            p1.width = cursorTextWidth / 2;
            p1.leftMargin = tabChildWidth / 4;
            this.tabCursor.requestLayout();
        }

        /**
         * 切换Tab视图
         *
         * @param position 切换位置
         */
        public void changeView(int position, TextView tvBusinesstvProgram, TextView tvBusinesstvHistory) {
            if (position == currentIndex) {
                return;
            }
            int fromXDelta = tabChildWidth * viewPager.getCurrentItem();
            int toXDelta = tabChildWidth * position;
            TranslateAnimation animation = new TranslateAnimation((float) fromXDelta, (float) toXDelta, 0.0F, 0.0F);
            animation.setFillAfter(true);
            animation.setDuration(500L);
            this.tabCursor.startAnimation(animation);

            switch (currentIndex) {
                case 0:
                    tvBusinesstvProgram.setTextColor(ContextCompat.getColor(mActivity, R.color.colorDark));
                    break;
                case 1:
                    tvBusinesstvHistory.setTextColor(ContextCompat.getColor(mActivity, R.color.colorDark));
                    break;
            }

            switch (position) {
                case 0:
                    tvBusinesstvProgram.setTextColor(ContextCompat.getColor(mActivity, R.color.colorTheme));
                    break;
                case 1:
                    tvBusinesstvHistory.setTextColor(ContextCompat.getColor(mActivity, R.color.colorTheme));
                    break;
            }

            viewPager.setCurrentItem(position);
            currentIndex = position;
        }

        public void onStartLoadMore() {
            int index = -1;
            if (adapters != null && adapters.size() == 2 && adapters.get(0).getDataCount() > 0) {
                BusinessInfo businessInfo = (BusinessInfo) adapters.get(0).getItem(adapters.get(0).getDataCount() - 1);
                index = businessInfo.index;
            }
            getCreateTvList(index);
        }

        /**
         * 设置是否有数据
         *
         * @param position 哪个视图
         */
        void isNoData(int position) {
            commonNoDatas.get(position).setVisibility(adapters.get(position).getDataCount() == 0 ? android.view.View.VISIBLE : android.view.View.GONE);
            commonLines.get(position).setVisibility(adapters.get(position).getDataCount() == 0 ? android.view.View.GONE : android.view.View.VISIBLE);
        }

        public void getRoomLiveUrl() {
            HttpUtils.getRoomLiveUrl("chuangtv", new HttpCallback<String>() {
                @Override
                public void onSuccess(String s) {
                    mView.startLive(s);
                }
            });
        }

        private void getCreateTvList(int lastIndex) {
            HttpUtils.getCreateTvList(lastIndex, new HttpCallback<List<BusinessInfo>>() {
                @Override
                public void onSuccess(List<BusinessInfo> businessInfos) {

                    List<BusinessInfo> businesstvProgramList = new ArrayList<>();
                    List<BusinessInfo> businesstvHistoryList = new ArrayList<>();

                    for (int i = 0; i < businessInfos.size(); i++) {
                        BusinessInfo businessInfo = businessInfos.get(i);
                        if (businessInfo.status == 1) {
                            businesstvHistoryList.add(businessInfo);
                        } else {
                            businesstvProgramList.add(businessInfo);
                        }
                    }

                    adapters.get(0).clearDatas();
                    adapters.get(1).clearDatas();

                    adapters.get(0).notifyDataChangedAfterLoadMore(businesstvProgramList);
                    adapters.get(1).notifyDataChangedAfterLoadMore(businesstvHistoryList);

                    if (businesstvProgramList != null && businesstvProgramList.size() > 0 && businesstvProgramList.get(0).status == 2) {
                        startCountDownTimer(businesstvProgramList.get(0).remain_time * 1000);
                    }
                }

                @Override
                public void onError(String strMsg) {
                    super.onError(strMsg);
                }

                @Override
                public void onFinish() {
                    super.onFinish();
                    onFinishAsync();
                    isNoData(0);
                    isNoData(1);
                }
            });
        }

        private void getCreateTvReservation(int postion, int index, String tvp_id) {
            HttpUtils.getCreateTvReservation(index, tvp_id, new HttpCallback<Boolean>(postion) {

                @Override
                public void onStart() {
                    super.onStart();
                    onStartAsync();
                }

                @Override
                public void onSuccess(Boolean result) {
                    if ((boolean) result) {
                        int postion = (int) data;
                        BusinessInfo businessInfo = (BusinessInfo) adapters.get(0).getItem(postion);
                        businessInfo.is_reservation = true;
                        adapters.get(0).notifyDataSetChanged();
                        showMessage("您已成功预约,将在节目开始5分钟前提醒您");
                    } else {
                        showMessage("预约失败");
                    }
                }

                @Override
                public void onError(String strMsg) {
                    super.onError(strMsg);
                    showMessage(strMsg);
                }

                @Override
                public void onFinish() {
                    super.onFinish();
                    onFinishAsync();
                }
            });
        }

        public void startCountDownTimer(int totleTime) {
            cancelCountDownTimer();
            mCountDownTimer = new CountDownTimer(totleTime, 1000) {
                @Override
                public void onTick(long millisUntilFinished) {
                    Logger.e("CountDownTimer onTick:" + millisUntilFinished);
                }

                @Override
                public void onFinish() {
                    if (adapters.get(0).getDataCount() == 1) {
                        getCreateTvList(-1);
                    } else {
                        BusinessInfo businessInfo = (BusinessInfo) adapters.get(0).getItem(0);
                        businessInfo.status = 1;
                        businessInfo.remain_time = 0;
                        BusinessInfo nextBusinessInfo = (BusinessInfo) adapters.get(0).getItem(1);
                        nextBusinessInfo.status = 2;

                        adapters.get(0).removeItem(0);
                        adapters.get(1).addData(adapters.get(1).getDataCount(), businessInfo);

                        adapters.get(0).notifyDataSetChanged();
                        adapters.get(1).notifyDataSetChanged();
                        startCountDownTimer(nextBusinessInfo.remain_time * 1000);
                    }
                }
            };
            mCountDownTimer.start();
        }

        public void cancelCountDownTimer() {
            if (mCountDownTimer != null) {
                mCountDownTimer.cancel();
                mCountDownTimer = null;
            }
        }

//        public void goPlayItem() {
//            RecyclerView.LayoutManager layoutManager = commonRecycler.getLayoutManager();
//            if (layoutManager instanceof LinearLayoutManager) {
//                LinearLayoutManager linearManager = (LinearLayoutManager) layoutManager;
//                if (commonRecycler.getAdapter().getItemCount() > 1) {
//                    linearManager.scrollToPositionWithOffset(postion, 0);
//                    linearManager.setStackFromEnd(true);
//                }
//            }
//        }

        @Override
        public void onDestroy() {
            cancelCountDownTimer();
            super.onDestroy();
        }
    }

    class BusinessTVAdapter extends BaseRecyclerAdapter<BusinessInfo> {

        private Activity mActivity;

        public BusinessTVAdapter(Activity activity) {
            super(activity, R.layout.item_businesstv);
            this.mActivity = activity;
        }

        @Override
        protected void setItemData(ViewHolderHelper viewHolderHelper, int i, BusinessInfo businessInfo) {
            LinearLayout llBusinessTVContent = viewHolderHelper.getView(R.id.ll_businesstv_content);
            ImageView ivBusinessTVFace = viewHolderHelper.getView(R.id.iv_businesstv_face);
            TextView tvBusinessTVName = viewHolderHelper.getView(R.id.tv_businesstv_name);
            TextView tvBusinessTVGoodat = viewHolderHelper.getView(R.id.tv_businesstv_goodat);
            TextView tvBusinessTVOther = viewHolderHelper.getView(R.id.tv_businesstv_other);
            TextView tvBusinessTVConsult = viewHolderHelper.getView(R.id.tv_businesstv_consult);
            TextView tvBusinessTVTime = viewHolderHelper.getView(R.id.tv_businesstv_time);
            TextView tvBusinessTVState = viewHolderHelper.getView(R.id.tv_businesstv_state);

            GlideUtils.getNormalIamgeToUrl(mActivity, businessInfo.thumbnail, ivBusinessTVFace, R.drawable.image_def);
            tvBusinessTVName.setText(businessInfo.title);
            tvBusinessTVGoodat.setText(businessInfo.custname);
            tvBusinessTVOther.setText(businessInfo.desc);

            tvBusinessTVTime.setText(DateTimeUtils.getLiveTime(businessInfo.st * 1000));

            viewHolderHelper.setItemChildClickListener(R.id.iv_businesstv_face);
            viewHolderHelper.setItemChildClickListener(R.id.tv_businesstv_name);
            viewHolderHelper.setItemChildClickListener(R.id.tv_businesstv_goodat);
            viewHolderHelper.setItemChildClickListener(R.id.tv_businesstv_other);
            viewHolderHelper.setItemChildClickListener(R.id.tv_businesstv_consult);

            viewHolderHelper.setText(R.id.tv_businesstv_money, "投资金额：" + businessInfo.investment);
            viewHolderHelper.setText(R.id.tv_businesstv_address, "所在地区：" + businessInfo.area);

            switch (businessInfo.status) {
                case 1:
                    llBusinessTVContent.setBackgroundResource(R.drawable.businesstv_round_line_transparent);
                    tvBusinessTVTime.setBackgroundResource(R.drawable.round_pie_gray_transparent);
                    tvBusinessTVState.setBackgroundResource(R.drawable.round_pie_gray_transparent);

                    tvBusinessTVState.setText("已播完");
                    viewHolderHelper.setVisibility(R.id.tv_businesstv_state, android.view.View.VISIBLE);
                    viewHolderHelper.setVisibility(R.id.v_businesstv_line, android.view.View.VISIBLE);

                    tvBusinessTVConsult.setBackgroundResource(R.drawable.round10_line_theme);
                    tvBusinessTVConsult.setText("回看视频");
                    tvBusinessTVConsult.setTextColor(ContextCompat.getColor(mContext, R.color.colorTheme));
                    break;
                case 2:
                    llBusinessTVContent.setBackgroundResource(R.drawable.businesstv_round_line_red_shadow);
                    tvBusinessTVTime.setBackgroundResource(R.drawable.businesstv_round_pie_orange_red_gradient);
                    tvBusinessTVState.setBackgroundResource(R.drawable.businesstv_round_pie_red_orange_gradient);

                    tvBusinessTVState.setText("直播中");
                    viewHolderHelper.setVisibility(R.id.tv_businesstv_state, android.view.View.VISIBLE);
                    viewHolderHelper.setVisibility(R.id.v_businesstv_line, android.view.View.VISIBLE);

                    tvBusinessTVConsult.setBackgroundResource(R.drawable.round10_pie_theme);
                    tvBusinessTVConsult.setText("查看项目");
                    tvBusinessTVConsult.setTextColor(ContextCompat.getColor(mContext, R.color.colorLight));

                    break;
                default:
                    llBusinessTVContent.setBackgroundResource(R.drawable.businesstv_round_line_transparent);
                    tvBusinessTVTime.setBackgroundResource(R.drawable.round_pie_gray_transparent);
                    viewHolderHelper.setVisibility(R.id.tv_businesstv_state, android.view.View.GONE);
                    viewHolderHelper.setVisibility(R.id.v_businesstv_line, android.view.View.GONE);

                    tvBusinessTVConsult.setBackgroundResource(R.drawable.round10_line_theme);
                    tvBusinessTVConsult.setText(!businessInfo.is_reservation ? "节目预约" : "已预约");
                    tvBusinessTVConsult.setTextColor(ContextCompat.getColor(mContext, R.color.colorTheme));
                    break;
            }
        }

    }
}

